<?php
namespace app\common\controller;

use think\auth\Auth;
use think\Loader;
use think\Controller;

/**
* 后台公用基础控制器
* @author Kaisa
* @version 2017-02-09
*/
class AdminBaseController extends Controller {
	
    protected function _initialize() {
        parent::_initialize();
        $this->checkAuth();
        $this->getMenu();
		// 当前路径URL，菜单用到
		$this->assign('current_url', Loader::parseName(request()->controller().'/'.request()->action()));
		// 判断重复状态
//		$user = db('user')->field('session_id')->where('id', session('admin_id'))->find();
//		if($user['session_id'] != session_id()){
//			session('admin_id', null);
//			session('admin_name', null);
//			$this->success('该账号已在别处登录！', 'admin/login/index');
//		}
		// 配置
		if (cache('site_config')) {
			$site_config = cache('site_config');
		} else {
			$site_config = get_config('site_config');
		}
		config($site_config);
		$this->check_act();
    }
	/**
	 * 判断是否显示后台左边菜单
	 */
	public function check_act(){
		$request = \think\Request::instance();
		$controller=strtolower($request->controller());
		$array_controller=array("index");
		$action=$request->action();
		$is_show_left=0;
		if(!in_array($controller, $array_controller)){
			$is_show_left=1;
		}
		$this->assign("is_show_left",$is_show_left);
	}
    /**
     * 权限检查
     * @return bool
     */
    protected function checkAuth() {
		$admin_id = session('admin_id');
        if (!$admin_id) {
            $this->redirect('admin/login/index');
        }

		$url = request()->module() . '/' . request()->controller() . '/' . request()->action();
        // 排除权限
        $not_check = ['admin/Index/index', 'admin/Index/update', 'admin/AuthGroup/getjson', 'admin/Index/password', 'admin/Index/hello', 'admin/Index/clear'];
		// 排除管理员ID
		$not_check_id = [1];
        if (!in_array($url, $not_check) && !in_array($admin_id, $not_check_id)) {
            $auth = new Auth();
            if (!$auth->check($url, $admin_id)) {
                $this->error('没有权限');
            }
        }
    }

    /**
     * 获取侧边栏菜单
     */
    protected function getMenu() {
        $menu     = [];
        $admin_id = session('admin_id');
        $auth     = new Auth();
        $auth_rule_list = db('auth_rule')->where('status', 1)->order(['sort' => 'asc', 'id' => 'asc'])->select();
        foreach ($auth_rule_list as $value) {
            if ($auth->check($value['name'], $admin_id) || $admin_id == 1) {
                $menu[] = $value;
            }
        }
        $menu = !empty($menu) ? array2tree($menu) : [];
        $this->assign('menu', $menu);
    }
}
